package cn.com.cetccst.appshield.ui;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;

import cn.com.cetccst.appshield.AppShieldManager;
import cn.com.cetccst.appshield.BR;
import cn.com.cetccst.appshield.R;
import cn.com.cetccst.appshield.databinding.FragmentAppShieldBinding;
import cn.com.cetccst.appshield.ui.model.AppShieldViewModel;
import cn.com.cetccst.datacenter.policy.entity.BWAppEntity;
import cn.com.cetccst.datacenter.policy.type.BlackWhiteAppSetting;
import cn.com.cetccst.uicomponents.binding.app.DataBindingConfig;
import cn.com.cetccst.uicomponents.binding.app.DataBindingFragment;

public class AppShieldFragment extends DataBindingFragment<FragmentAppShieldBinding> {
    private AppShieldViewModel viewModel;
    private Observer<BlackWhiteAppSetting> observer;
    private AppInfoListAdapter adapter;

    @Override
    protected void initViewModel() {
        viewModel = getFragmentScopeViewModel(AppShieldViewModel.class);
        adapter = new AppInfoListAdapter(getContext(), item -> {
           //TODO item点击后的处理
        });
    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        return new DataBindingConfig(R.layout.fragment_app_shield, BR.viewModel, viewModel)
                .addBindingParam(BR.adapter, adapter);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        //应用商店的应用需要绑定appmodel，当数据变化时需要通知adapter更新UI
        observer = blackWhiteAppSetting -> viewModel.setAppConfig(getContext(), getViewLifecycleOwner(), blackWhiteAppSetting, entity -> adapter.notifyItemChanged(adapter.getCurrentList().indexOf(entity)));

        AppShieldManager.getInstance().getBlackWhiteAppSetting().observe(getViewLifecycleOwner(), observer);
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        AppShieldManager.getInstance().getBlackWhiteAppSetting().removeObserver(observer);
    }

    public interface OnFragmentInteractionListener {
        void onListFragmentInteraction(BWAppEntity item);
    }
}
